document.addEventListener('DOMContentLoaded', function() {
    // Initialize tabs
    initializeTabs();
    
    // Check if user is authenticated
    checkAuthentication();

    // Add event listeners
    document.getElementById('lockButton').addEventListener('click', lockManager);
    document.getElementById('addPassword').addEventListener('click', showAddPasswordForm);
    document.getElementById('generateButton')?.addEventListener('click', generateNewPassword);
    document.getElementById('copyButton')?.addEventListener('click', copyGeneratedPassword);
    document.getElementById('exportData')?.addEventListener('click', exportPasswords);
    document.getElementById('importData')?.addEventListener('click', importPasswords);
    
    // Initialize search functionality
    const searchBox = document.querySelector('.search-box');
    searchBox.addEventListener('input', function(e) {
        filterPasswords(e.target.value);
    });

    // Load passwords if authenticated
    loadPasswords();
});

function initializeTabs() {
    const tabs = document.querySelectorAll('.tab');
    tabs.forEach(tab => {
        tab.addEventListener('click', () => {
            const targetId = tab.getAttribute('data-tab');
            
            // Update active tab
            document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
            tab.classList.add('active');
            
            // Show target content
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });
            document.getElementById(targetId).classList.add('active');
        });
    });
}

function checkAuthentication() {
    chrome.storage.local.get(['isLocked', 'masterPasswordHash'], function(result) {
        if (!result.masterPasswordHash) {
            showSetupMasterPassword();
        } else if (result.isLocked || result.isLocked === undefined) {
            showMasterPasswordPrompt();
        }
    });
}

function showSetupMasterPassword() {
    const container = document.querySelector('.container');
    container.innerHTML = `
        <h2>欢迎使用密码管理器</h2>
        <p>请设置您的主密码：</p>
        <input type="password" id="newMasterPass" class="search-box" placeholder="输入主密码">
        <input type="password" id="confirmMasterPass" class="search-box" placeholder="确认主密码">
        <div id="passwordStrength"></div>
        <button id="setupButton" class="button">设置主密码</button>
    `;
    
    const newPassInput = document.getElementById('newMasterPass');
    newPassInput.addEventListener('input', checkPasswordStrength);
    document.getElementById('setupButton').addEventListener('click', setupMasterPassword);
}

function checkPasswordStrength(e) {
    const password = e.target.value;
    const strength = calculatePasswordStrength(password);
    const strengthDiv = document.getElementById('passwordStrength');
    strengthDiv.innerHTML = `密码强度: ${strength.score}/100 - ${strength.label}`;
}

function calculatePasswordStrength(password) {
    let score = 0;
    
    // Length
    score += Math.min(password.length * 4, 40);
    
    // Character types
    if (/[A-Z]/.test(password)) score += 15;
    if (/[a-z]/.test(password)) score += 15;
    if (/[0-9]/.test(password)) score += 15;
    if (/[^A-Za-z0-9]/.test(password)) score += 15;
    
    let label = '弱';
    if (score >= 90) label = '非常强';
    else if (score >= 70) label = '强';
    else if (score >= 40) label = '中等';
    
    return { score, label };
}

async function setupMasterPassword() {
    const newPass = document.getElementById('newMasterPass').value;
    const confirmPass = document.getElementById('confirmMasterPass').value;
    
    if (newPass !== confirmPass) {
        alert('两次输入的密码不匹配！');
        return;
    }
    
    const strength = calculatePasswordStrength(newPass);
    if (strength.score < 40) {
        if (!confirm('这个密码强度较弱。您确定要使用吗？')) {
            return;
        }
    }
    
    const hashBuffer = await crypto.subtle.digest('SHA-256', 
        new TextEncoder().encode(newPass));
    const hashArray = Array.from(new Uint8Array(hashBuffer));
    const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
    
    chrome.storage.local.set({
        masterPasswordHash: hashHex,
        isLocked: false
    }, function() {
        location.reload();
    });
}

function showMasterPasswordPrompt() {
    const container = document.querySelector('.container');
    container.innerHTML = `
        <h2>输入主密码</h2>
        <input type="password" id="masterPassword" class="search-box">
        <button id="unlockButton" class="button">解锁</button>
    `;
    
    document.getElementById('unlockButton').addEventListener('click', unlock);
    document.getElementById('masterPassword').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') unlock();
    });
}

async function unlock() {
    const masterPassword = document.getElementById('masterPassword').value;
    const hashBuffer = await crypto.subtle.digest('SHA-256', 
        new TextEncoder().encode(masterPassword));
    const hashArray = Array.from(new Uint8Array(hashBuffer));
    const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
    
    chrome.storage.local.get(['masterPasswordHash'], function(result) {
        if (hashHex === result.masterPasswordHash) {
            chrome.storage.local.set({isLocked: false}, function() {
                location.reload();
            });
        } else {
            alert('主密码不正确！');
        }
    });
}

function lockManager() {
    chrome.storage.local.set({isLocked: true}, function() {
        location.reload();
    });
}

function loadPasswords() {
    chrome.storage.local.get(['passwords'], function(result) {
        const passwordList = document.getElementById('passwordList');
        const passwords = result.passwords || [];
        
        if (passwords.length === 0) {
            passwordList.innerHTML = '<div class="password-item">没有保存密码</div>';
            return;
        }
        
        passwords.forEach(password => {
            const passwordElement = createPasswordElement(password);
            passwordList.appendChild(passwordElement);
        });
        
        updateSecurityScore(passwords);
    });
}

function createPasswordElement(password) {
    const div = document.createElement('div');
    div.className = 'password-item';
    div.innerHTML = `
        <div>
            <strong>${password.website}</strong>
            <div>${password.username}</div>
        </div>
        <div>
            <button class="button" onclick="copyPassword('${password.id}')">复制</button>
            <button class="button" onclick="editPassword('${password.id}')">编辑</button>
            <button class="button" onclick="deletePassword('${password.id}')">删除</button>
        </div>
    `;
    return div;
}

function generateNewPassword() {
    const length = parseInt(document.getElementById('passLength').value);
    const useUpper = document.getElementById('useUppercase').checked;
    const useLower = document.getElementById('useLowercase').checked;
    const useNumbers = document.getElementById('useNumbers').checked;
    const useSymbols = document.getElementById('useSymbols').checked;
    
    let charset = '';
    if (useUpper) charset += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    if (useLower) charset += 'abcdefghijklmnopqrstuvwxyz';
    if (useNumbers) charset += '0123456789';
    if (useSymbols) charset += '!@#$%^&*()_+-=[]{}|;:,.<>?';
    
    if (charset === '') {
        alert('请至少选择一种字符类型');
        return;
    }
    
    let password = '';
    for (let i = 0; i < length; i++) {
        password += charset.charAt(Math.floor(Math.random() * charset.length));
    }
    
    document.getElementById('generatedPassword').value = password;
}

function copyGeneratedPassword() {
    const password = document.getElementById('generatedPassword').value;
    if (!password) {
        alert('请先生成密码！');
        return;
    }
    
    navigator.clipboard.writeText(password).then(() => {
        alert('密码已复制到剪贴板！');
        // Clear clipboard after 30 seconds
        setTimeout(() => {
            navigator.clipboard.writeText('');
        }, 30000);
    });
}

function exportPasswords() {
    chrome.storage.local.get(['passwords'], function(result) {
        const passwords = result.passwords || [];
        const exportData = {
            passwords: passwords,
            exportDate: new Date().toISOString()
        };
        
        const blob = new Blob([JSON.stringify(exportData, null, 2)], {type: 'application/json'});
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `password_manager_export_${new Date().toISOString().split('T')[0]}.json`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    });
}

function importPasswords() {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.json';
    
    input.onchange = e => {
        const file = e.target.files[0];
        const reader = new FileReader();
        
        reader.onload = function(event) {
            try {
                const importData = JSON.parse(event.target.result);
                if (!importData.passwords || !Array.isArray(importData.passwords)) {
                    throw new Error('导入文件格式无效');
                }
                
                chrome.storage.local.get(['passwords'], function(result) {
                    const currentPasswords = result.passwords || [];
                    const newPasswords = [...currentPasswords];
                    
                    importData.passwords.forEach(importPass => {
                        const exists = newPasswords.findIndex(p => 
                            p.website === importPass.website && 
                            p.username === importPass.username
                        );
                        
                        if (exists === -1) {
                            newPasswords.push(importPass);
                        }
                    });
                    
                    chrome.storage.local.set({passwords: newPasswords}, function() {
                        alert('密码导入成功！');
                        location.reload();
                    });
                });
            } catch (error) {
                alert('导入密码时出错：' + error.message);
            }
        };
        
        reader.readAsText(file);
    };
    
    input.click();
}

function updateSecurityScore(passwords) {
    if (!passwords.length) return;
    
    let score = 100;
    let weakPasswords = 0;
    let reusedPasswords = 0;
    let oldPasswords = 0;
    
    // Check password strength and reuse
    const passwordCounts = {};
    passwords.forEach(pass => {
        const strength = calculatePasswordStrength(pass.password);
        if (strength.score < 40) weakPasswords++;
        
        passwordCounts[pass.password] = (passwordCounts[pass.password] || 0) + 1;
        if (passwordCounts[pass.password] > 1) reusedPasswords++;
        
        // Check password age if timestamp exists
        if (pass.timestamp) {
            const age = (new Date() - new Date(pass.timestamp)) / (1000 * 60 * 60 * 24); // days
            if (age > 90) oldPasswords++; // older than 90 days
        }
    });
    
    // Update security score
    score -= (weakPasswords * 10);
    score -= (reusedPasswords * 15);
    score -= (oldPasswords * 5);
    score = Math.max(0, Math.min(100, score));
    
    // Update UI
    const scoreElement = document.querySelector('.score-fill');
    if (scoreElement) {
        scoreElement.style.width = score + '%';
        scoreElement.parentElement.nextElementSibling.textContent = score + '%';
    }
    
    // Update checklist
    const checklist = document.getElementById('securityChecklist');
    if (checklist) {
        checklist.querySelector('ul').innerHTML = `
            <li>弱密码 (${weakPasswords} 个)</li>
            <li>重复密码 (${reusedPasswords} 个)</li>
            <li>旧密码 (${oldPasswords} 个)</li>
        `;
    }
}

function filterPasswords(query) {
    const items = document.querySelectorAll('.password-item');
    items.forEach(item => {
        const text = item.textContent.toLowerCase();
        if (text.includes(query.toLowerCase())) {
            item.style.display = 'block';
        } else {
            item.style.display = 'none';
        }
    });
}

function showAddPasswordForm() {
    const container = document.querySelector('.container');
    container.innerHTML = `
        <h2>添加新密码</h2>
        <input type="text" id="website" class="search-box" placeholder="网站">
        <input type="text" id="username" class="search-box" placeholder="用户名">
        <input type="password" id="password" class="search-box" placeholder="密码">
        <button id="savePassword" class="button">保存</button>
        <button id="generatePassword" class="button">生成密码</button>
        <button onclick="location.reload()" class="button">取消</button>
    `;
    
    document.getElementById('savePassword').addEventListener('click', saveNewPassword);
    document.getElementById('generatePassword').addEventListener('click', generatePassword);
}

function saveNewPassword() {
    const website = document.getElementById('website').value;
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    
    if (!website || !username || !password) {
        alert('请填写所有字段');
        return;
    }
    
    chrome.storage.local.get(['passwords'], function(result) {
        const passwords = result.passwords || [];
        passwords.push({
            id: Date.now().toString(),
            website,
            username,
            password: encrypt(password) // TODO: Implement encryption
        });
        
        chrome.storage.local.set({passwords}, function() {
            location.reload();
        });
    });
}

function generatePassword() {
    const length = 16;
    const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+";
    let password = "";
    for (let i = 0; i < length; i++) {
        password += charset.charAt(Math.floor(Math.random() * charset.length));
    }
    document.getElementById('password').value = password;
}

// TODO: Implement proper encryption/decryption
function encrypt(text) {
    return text; // Placeholder
}

function decrypt(text) {
    return text; // Placeholder
}
